package org.jeecg.modules.demo.dtwlwjc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.dtwlwjc.entity.ZwglEquipmentStatus;
import org.jeecg.modules.demo.dtwlwjc.entity.ZwglStatisticalData;
import org.jeecg.modules.demo.dtwlwjc.mapper.ZwglEquipmentStatusMapper;
import org.jeecg.modules.demo.dtwlwjc.mapper.ZwglStatisticalDataMapper;
import org.jeecg.modules.demo.dtwlwjc.service.IZwglStatisticalDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 综合数据
 * @Author: jeecg-boot
 * @Date: 2023-04-17
 * @Version: V1.0
 */
@Service
public class ZwglStatisticalDataServiceImpl extends ServiceImpl<ZwglStatisticalDataMapper, ZwglStatisticalData> implements IZwglStatisticalDataService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ZwglStatisticalDataMapper zwglStatisticalDataMapper;
    @Autowired
    private ZwglPestCountServiceImpl zwglPestCountService;
    @Autowired
    private ZwglEquipmentStatusMapper zwglEquipmentStatusMapper;

    @Override
    public String getdtsj() {

        String[] arr;
        arr = new String[12];
        arr[0] = "0511220007";
        arr[1] = "0512220003";
        arr[2] = "0511220001";
        arr[3] = "0511220008";
        arr[4] = "0511220006";
        arr[5] = "0514220002";
        arr[6] = "0512220005";
        arr[7] = "0512220006";
        arr[8] = "0514220001";
        arr[9] = "0514220004";
        arr[10] = "0511220002";
        arr[11] = "0511220003";
        for (int i = 0; i < arr.length; i++) {

            //得到long类型当前时间
            long l = System.currentTimeMillis();
            //new日期对象
            Date date = new Date(l);
            Date date1 = new Date(l);
            //转换提日期输出格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time1 = dateFormat1.format(date1);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            //调用的api的接口地址
            String deviceAddr = arr[i];
            String startTime = dateFormat.format(calendar.getTime());
            String endTime = time;

            String apiPath = "http://farm.0531yun.cn/UserDevice/WormAnalyzeReport?deviceAddr=" + deviceAddr + "&startTime=" + startTime + "&endTime=" + endTime;
            BufferedReader in = null;
            StringBuffer result = null;
            String token = (String) redisUtil.get("dttoken");
            if (Objects.isNull(token)) {
                zwglPestCountService.getToken();
            }

            try {
                URL url = new URL(apiPath);
                //打开和url之间的连接

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);


                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("token", token);
                connection.setRequestProperty("Charset", "utf-8");
                connection.connect();
                result = new StringBuffer();
                //读取URL的响应
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                String result2 = result.toString(); //返回json字符串

                //获取数据
                JSONObject jsonObject = JSON.parseObject(result2);

                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(j);
                    JSONObject jsonObject2 = jsonObject1.getJSONObject("wormDataAIDO");

                    JSONArray jsonArray1 = jsonObject2.getJSONArray("analyseData");
                    for (int k = 0; k < jsonArray1.size(); k++) {
                        JSONObject jsonObject3 = jsonArray1.getJSONObject(k);


                        ZwglStatisticalData zwglStatisticalData = new ZwglStatisticalData();
                        zwglStatisticalData.setDevictNo(jsonObject1.getString("deviceAddr"));
                        zwglStatisticalData.setPhoto(jsonObject1.getString("imagesUrl"));
                        zwglStatisticalData.setHcmc(jsonObject3.getString("name"));
                        zwglStatisticalData.setHcsl(jsonObject3.getString("num"));
                        zwglStatisticalData.setCysj(time1);
                        zwglStatisticalDataMapper.insert(zwglStatisticalData);


                    }


                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
        return null;
    }

    @Override
    public Result getcqlist(String deviceNo) {
        QueryWrapper<ZwglStatisticalData> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ZwglEquipmentStatus> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("device_status", deviceNo);
        List<ZwglEquipmentStatus> list1 = zwglEquipmentStatusMapper.selectList(queryWrapper1);
        String deviceNoa = null;
        for (ZwglEquipmentStatus zwglEquipmentStatus : list1) {
            deviceNoa = zwglEquipmentStatus.getDeviceName();
        }
        queryWrapper.eq("devict_no", deviceNoa);
        queryWrapper.orderByDesc("cysj");
//        queryWrapper.last("LIMIT 10");
        List<ZwglStatisticalData> list = zwglStatisticalDataMapper.selectList(queryWrapper);
        return Result.OK(list);
    }
    @Override
    public Result countCategories() {
        LambdaQueryWrapper<ZwglStatisticalData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(ZwglStatisticalData::getHcmc)
                .groupBy(ZwglStatisticalData::getHcmc);
        List<Map<String, Object>> list = zwglStatisticalDataMapper.selectMaps(queryWrapper);
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("totalCategories", list.size());
        return Result.OK(resultMap);
    }

    @Override
    public Result getcqlista(String deviceNo, Integer pageNo) {
        QueryWrapper<ZwglStatisticalData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("devict_no", deviceNo);
        queryWrapper.orderByDesc("cysj");
        Page<ZwglStatisticalData> page = new Page<>(pageNo, 8);
        Page<ZwglStatisticalData> list=zwglStatisticalDataMapper.selectPage(page,queryWrapper);
        return Result.OK(list);
    }

    @Override
    public Result getcqsbbh() {
        QueryWrapper<ZwglStatisticalData> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("devict_no");
        List<ZwglStatisticalData> list = zwglStatisticalDataMapper.selectList(queryWrapper);
        return Result.OK(list);
    }

    @Override
    public Result shijianduancq(String kaishishijian, String jieshushijian, String deviceNo) {
        QueryWrapper<ZwglStatisticalData> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ZwglEquipmentStatus> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("device_status", deviceNo);
        List<ZwglEquipmentStatus> list1 = zwglEquipmentStatusMapper.selectList(queryWrapper1);
        String deviceNoa = null;
        for (ZwglEquipmentStatus zwglEquipmentStatus : list1) {
            deviceNoa = zwglEquipmentStatus.getDeviceName();
        }
        queryWrapper.between("cysj",kaishishijian+" 00:00:00",jieshushijian+" 23:59:59");
        queryWrapper.eq("devict_no",deviceNoa);
//        queryWrapper.last("limit 6");
        List<ZwglStatisticalData> list=zwglStatisticalDataMapper.selectList(queryWrapper);
        return Result.OK(list);

    }
    @Override
    public Result chongqing(String starttime, String endtime, String deviceNo, Integer pageNo) {
        QueryWrapper<ZwglStatisticalData> queryWrapper=new QueryWrapper<>();
        queryWrapper.between("cysj",starttime,endtime);
        queryWrapper.eq("devict_no",deviceNo);
        Page<ZwglStatisticalData> page = new Page<>(pageNo,8);
        Page<ZwglStatisticalData> list=zwglStatisticalDataMapper.selectPage(page,queryWrapper);
        return Result.OK(list);

    }

}
